from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch

from app_settings import *
from html_code    import *
from facebook_sdk import Facebook

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(html_code)

    def post(self):
        self.response.headers['Content-Type'] = 'text/html'
        request_ids = self.request.get('request_ids', '')
        s = self.request.get('s', '')
        signed_request = self.request.get('signed_request', '')
        if request_ids or s:
            if request_ids and signed_request:
                fb = Facebook(app_id = app_id, app_secret=app_secret)
                fb.load_signed_request(signed_request)
                try:
                    app_requests = fb.api(u'/me/apprequests')
                except:
                    pass
                else:
                    if app_requests.get(u'data'):
                        del_req = app_requests.get(u'data')[0],get(u'id')
                        if del_req:
                            del_url = 'https://graph.facebook.com/%s?access_token=%s\
                                    &method=delete' % (del_req, fb.access_token)
                            urlfetch.fetch(del_url)
                self.response.out.write(html_code)
            else:
                self.response.out.write(html_code)
        elif signed_request:
            self.response.out.write(html_code)
        else:
            self.response.out.write('<script>top.location = "%s";</script>' % fan_page_url)            

application = webapp.WSGIApplication(
        [('/2', MainPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
